/**
 * @file 异步任务 IPC 处理器
 * @description 处理渲染进程发送的异步任务相关 IPC 请求
 * @author AI Assistant
 * @version 1.0.0
 * @since 2025-10-30
 */

import type {
  AsyncTask,
  CreateAsyncTaskInput,
  DatabaseResult,
  QueryAsyncTaskParams,
  UpdateAsyncTaskInput
} from '~shared/types/async-task'
import type { ParsedAsyncTask } from '#/database'
import { ipcMain } from 'electron'
import { AsyncTaskService } from '#/database'

/** 将 ParsedAsyncTask 转换为可通过 IPC 传输的纯对象 */
function toDTO(task: ParsedAsyncTask): AsyncTask {
  return {
    id: task.id ?? 0,
    task_type: task.task_type,
    business_data: task.business_data,
    status: task.status,
    progress: task.progress,
    error_message: task.error_message,
    result_data: task.result_data,
    created_at: task.created_at.getTime(),
    updated_at: task.updated_at.getTime(),
    started_at: task.started_at ? task.started_at.getTime() : null,
    completed_at: task.completed_at ? task.completed_at.getTime() : null
  }
}

/** 将共享的查询参数转换为服务层参数 */
function adaptQueryParams(params: QueryAsyncTaskParams) {
  return {
    ...params,
    created_after: params.created_after ? new Date(params.created_after) : undefined,
    created_before: params.created_before ? new Date(params.created_before) : undefined
  }
}

/**
 * IPC 通道名称常量
 */
export const ASYNC_TASK_CHANNELS = {
  // 创建操作
  CREATE_TASK: 'async-task:create-task',

  // 删除操作
  DELETE_TASK: 'async-task:delete-task',
  DELETE_TASKS: 'async-task:delete-tasks',
  CLEAR_ALL_TASKS: 'async-task:clear-all-tasks',

  // 查询操作
  FIND_BY_ID: 'async-task:find-by-id',
  QUERY_TASKS: 'async-task:query-tasks',
  GET_PENDING_TASKS: 'async-task:get-pending-tasks',
  GET_IN_PROGRESS_TASKS: 'async-task:get-in-progress-tasks',
  GET_COMPLETED_TASKS: 'async-task:get-completed-tasks',
  GET_FAILED_TASKS: 'async-task:get-failed-tasks',
  GET_TASKS_BY_TYPE: 'async-task:get-tasks-by-type',
  GET_TASK_COUNT: 'async-task:get-task-count',

  // 更新操作
  UPDATE_TASK: 'async-task:update-task',
  UPDATE_PROGRESS: 'async-task:update-progress',
  MARK_AS_IN_PROGRESS: 'async-task:mark-as-in-progress',
  MARK_AS_COMPLETED: 'async-task:mark-as-completed',
  MARK_AS_FAILED: 'async-task:mark-as-failed',

  // 清理操作
  CLEANUP_COMPLETED_TASKS: 'async-task:cleanup-completed-tasks',
  CLEANUP_FAILED_TASKS: 'async-task:cleanup-failed-tasks'
} as const

/**
 * 注册异步任务相关的 IPC 处理器
 */
export function registerAsyncTaskHandlers(): void {
  const service = AsyncTaskService.getInstance()

  // ==================== 创建操作 ====================

  /**
   * 创建异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.CREATE_TASK,
    async (_, input: CreateAsyncTaskInput): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到创建异步任务请求: ${input.task_type}`)
        const res = await service.createTask(input)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '创建任务失败' }
      } catch (error) {
        console.error('❌ IPC 创建异步任务失败:', error)
        return {
          success: false,
          error: `IPC 创建异步任务失败: ${error}`
        }
      }
    }
  )

  // ==================== 删除操作 ====================

  /**
   * 删除异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.DELETE_TASK,
    async (_, id: number): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🗑️ 收到删除异步任务请求: ID ${id}`)
        return await service.deleteTaskByLegacyId(id)
      } catch (error) {
        console.error('❌ IPC 删除异步任务失败:', error)
        return {
          success: false,
          error: `IPC 删除异步任务失败: ${error}`
        }
      }
    }
  )

  /**
   * 批量删除异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.DELETE_TASKS,
    async (_, ids: number[]): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🗑️ 收到批量删除异步任务请求: ${ids.length} 条记录`)
        return await service.deleteTasksByLegacyIds(ids)
      } catch (error) {
        console.error('❌ IPC 批量删除异步任务失败:', error)
        return {
          success: false,
          error: `IPC 批量删除异步任务失败: ${error}`
        }
      }
    }
  )

  /**
   * 清空所有异步任务
   */
  ipcMain.handle(ASYNC_TASK_CHANNELS.CLEAR_ALL_TASKS, async (): Promise<DatabaseResult<void>> => {
    try {
      console.log('🧹 收到清空所有异步任务请求')
      return await service.clearAllTasks()
    } catch (error) {
      console.error('❌ IPC 清空所有异步任务失败:', error)
      return {
        success: false,
        error: `IPC 清空所有异步任务失败: ${error}`
      }
    }
  })

  // ==================== 查询操作 ====================

  /**
   * 根据ID查找异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.FIND_BY_ID,
    async (_, id: number): Promise<DatabaseResult<AsyncTask | null>> => {
      try {
        console.log(`🔍 收到根据ID查找异步任务请求: ID ${id}`)
        const res = await service.findByLegacyId(id)
        return res.success
          ? { success: true, data: res.data ? toDTO(res.data) : null }
          : { success: false, error: res.error }
      } catch (error) {
        console.error('❌ IPC 根据ID查找异步任务失败:', error)
        return {
          success: false,
          error: `IPC 根据ID查找异步任务失败: ${error}`
        }
      }
    }
  )

  /**
   * 查询异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.QUERY_TASKS,
    async (_, params: QueryAsyncTaskParams): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log('🔍 收到查询异步任务请求')
        const res = await service.queryTasks(adaptQueryParams(params))
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 查询异步任务失败:', error)
        return {
          success: false,
          error: `IPC 查询异步任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取待处理的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.GET_PENDING_TASKS,
    async (_, limit?: number): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log(`🔍 收到获取待处理任务请求: 限制 ${limit || 50} 条`)
        const res = await service.getPendingTasks(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取待处理任务失败:', error)
        return {
          success: false,
          error: `IPC 获取待处理任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取进行中的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.GET_IN_PROGRESS_TASKS,
    async (_, limit?: number): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log(`🔍 收到获取进行中任务请求: 限制 ${limit || 50} 条`)
        const res = await service.getInProgressTasks(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取进行中任务失败:', error)
        return {
          success: false,
          error: `IPC 获取进行中任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取已完成的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.GET_COMPLETED_TASKS,
    async (_, limit?: number): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log(`🔍 收到获取已完成任务请求: 限制 ${limit || 50} 条`)
        const res = await service.getCompletedTasks(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取已完成任务失败:', error)
        return {
          success: false,
          error: `IPC 获取已完成任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取失败的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.GET_FAILED_TASKS,
    async (_, limit?: number): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log(`🔍 收到获取失败任务请求: 限制 ${limit || 50} 条`)
        const res = await service.getFailedTasks(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取失败任务失败:', error)
        return {
          success: false,
          error: `IPC 获取失败任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 根据类型获取任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.GET_TASKS_BY_TYPE,
    async (_, taskType: string, limit?: number): Promise<DatabaseResult<AsyncTask[]>> => {
      try {
        console.log(`🔍 收到根据类型获取任务请求: ${taskType}`)
        const res = await service.getTasksByType(taskType, limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO), count: res.count }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 根据类型获取任务失败:', error)
        return {
          success: false,
          error: `IPC 根据类型获取任务失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取任务总数
   */
  ipcMain.handle(ASYNC_TASK_CHANNELS.GET_TASK_COUNT, async (): Promise<DatabaseResult<number>> => {
    try {
      console.log('🔍 收到获取任务总数请求')
      const res = await service.getTaskCount()
      return res.success ? { success: true, data: res.data } : { success: false, error: res.error }
    } catch (error) {
      console.error('❌ IPC 获取任务总数失败:', error)
      return {
        success: false,
        error: `IPC 获取任务总数失败: ${error}`
      }
    }
  })

  // ==================== 更新操作 ====================

  /**
   * 更新异步任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.UPDATE_TASK,
    async (_, input: UpdateAsyncTaskInput): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到更新异步任务请求: ID ${input.id}`)
        const { id, ...rest } = input
        const res = await service.updateTaskByLegacyId(id, rest)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '任务不存在' }
      } catch (error) {
        console.error('❌ IPC 更新异步任务失败:', error)
        return {
          success: false,
          error: `IPC 更新异步任务失败: ${error}`
        }
      }
    }
  )

  /**
   * 更新任务进度
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.UPDATE_PROGRESS,
    async (_, id: number, progress: number): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到更新任务进度请求: ID ${id}, 进度 ${progress}%`)
        const res = await service.updateProgressByLegacyId(id, progress)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '任务不存在' }
      } catch (error) {
        console.error('❌ IPC 更新任务进度失败:', error)
        return {
          success: false,
          error: `IPC 更新任务进度失败: ${error}`
        }
      }
    }
  )

  /**
   * 标记任务为进行中
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.MARK_AS_IN_PROGRESS,
    async (_, id: number): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到标记任务为进行中请求: ID ${id}`)
        const res = await service.markAsInProgressByLegacyId(id)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '任务不存在' }
      } catch (error) {
        console.error('❌ IPC 标记任务为进行中失败:', error)
        return {
          success: false,
          error: `IPC 标记任务为进行中失败: ${error}`
        }
      }
    }
  )

  /**
   * 标记任务为已完成
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.MARK_AS_COMPLETED,
    async (_, id: number, resultData?: Record<string, any>): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到标记任务为已完成请求: ID ${id}`)
        const res = await service.markAsCompletedByLegacyId(id, resultData)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '任务不存在' }
      } catch (error) {
        console.error('❌ IPC 标记任务为已完成失败:', error)
        return {
          success: false,
          error: `IPC 标记任务为已完成失败: ${error}`
        }
      }
    }
  )

  /**
   * 标记任务为失败
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.MARK_AS_FAILED,
    async (_, id: number, errorMessage: string): Promise<DatabaseResult<AsyncTask>> => {
      try {
        console.log(`📝 收到标记任务为失败请求: ID ${id}`)
        const res = await service.markAsFailedByLegacyId(id, errorMessage)
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '任务不存在' }
      } catch (error) {
        console.error('❌ IPC 标记任务为失败失败:', error)
        return {
          success: false,
          error: `IPC 标记任务为失败失败: ${error}`
        }
      }
    }
  )

  // ==================== 清理操作 ====================

  /**
   * 清理已完成的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.CLEANUP_COMPLETED_TASKS,
    async (_, olderThanDays?: number): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🧹 收到清理已完成任务请求: ${olderThanDays || 30} 天前`)
        return await service.cleanupCompletedTasks(olderThanDays)
      } catch (error) {
        console.error('❌ IPC 清理已完成任务失败:', error)
        return {
          success: false,
          error: `IPC 清理已完成任务失败: ${error}`
        }
      }
    }
  )

  /**
   * 清理失败的任务
   */
  ipcMain.handle(
    ASYNC_TASK_CHANNELS.CLEANUP_FAILED_TASKS,
    async (_, olderThanDays?: number): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🧹 收到清理失败任务请求: ${olderThanDays || 7} 天前`)
        return await service.cleanupFailedTasks(olderThanDays)
      } catch (error) {
        console.error('❌ IPC 清理失败任务失败:', error)
        return {
          success: false,
          error: `IPC 清理失败任务失败: ${error}`
        }
      }
    }
  )

  console.log('✅ 异步任务 IPC 处理器已注册')
}
